import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { PointsRecord, PointsApproval, PointsLedger } from '@/types/points'

export const usePointsStore = defineStore('points', () => {
  // 状态
  const records = ref<PointsRecord[]>([])
  const approvals = ref<PointsApproval[]>([])
  const ledgers = ref<PointsLedger[]>([])
  const loading = ref(false)

  // 计算属性
  const totalRecords = computed(() => records.value.length)
  const totalAddPoints = computed(() => 
    records.value
      .filter(record => record.pointsType === 'add' && record.status === 'approved')
      .reduce((sum, record) => sum + record.pointsValue, 0)
  )
  const totalDeductPoints = computed(() => 
    records.value
      .filter(record => record.pointsType === 'deduct' && record.status === 'approved')
      .reduce((sum, record) => sum + record.pointsValue, 0)
  )
  const netPoints = computed(() => totalAddPoints.value - totalDeductPoints.value)
  const pendingApprovals = computed(() => 
    approvals.value.filter(approval => approval.approvalStatus === 'pending').length
  )

  // 方法
  const addRecord = (record: PointsRecord) => {
    records.value.unshift(record)
  }

  const updateRecord = (id: string, updates: Partial<PointsRecord>) => {
    const index = records.value.findIndex(record => record.id === id)
    if (index !== -1) {
      records.value[index] = { ...records.value[index], ...updates }
    }
  }

  const deleteRecord = (id: string) => {
    const index = records.value.findIndex(record => record.id === id)
    if (index !== -1) {
      records.value.splice(index, 1)
    }
  }

  const addApproval = (approval: PointsApproval) => {
    approvals.value.unshift(approval)
  }

  const updateApproval = (id: string, updates: Partial<PointsApproval>) => {
    const index = approvals.value.findIndex(approval => approval.id === id)
    if (index !== -1) {
      approvals.value[index] = { ...approvals.value[index], ...updates }
    }
  }

  const getRecordsByUser = (userId: string) => {
    return records.value.filter(record => record.responsiblePersonId === userId)
  }

  const getRecordsByDepartment = (departmentId: string) => {
    return records.value.filter(record => record.departmentId === departmentId)
  }

  const getPendingApprovals = () => {
    return approvals.value.filter(approval => approval.approvalStatus === 'pending')
  }

  const getMyApprovals = (approverId: string) => {
    return approvals.value.filter(approval => approval.approverId === approverId)
  }

  return {
    // 状态
    records,
    approvals,
    ledgers,
    loading,
    
    // 计算属性
    totalRecords,
    totalAddPoints,
    totalDeductPoints,
    netPoints,
    pendingApprovals,
    
    // 方法
    addRecord,
    updateRecord,
    deleteRecord,
    addApproval,
    updateApproval,
    getRecordsByUser,
    getRecordsByDepartment,
    getPendingApprovals,
    getMyApprovals
  }
})
